package designpattern.demo.structural.proxypattern;


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 动态代理Demo
 */
public class DynamicProxy {

    public static void main(String[] args) {
        //定义一个people作为被代理的实例
        IPeople ple = new People();
        //定义一个handler
        InvocationHandler handle = new MyHandle(ple);

        //获得类加载器
        ClassLoader cl = ple.getClass().getClassLoader();

        //动态产生一个代理，下边两种方法均可
        //		IPeople p=(IPeople) Proxy.newProxyInstance(cl, new Class[]{IPeople.class}, handle);
        IPeople p = (IPeople) Proxy.newProxyInstance(cl, ple.getClass().getInterfaces(), handle);

        //执行被代理者的方法。
        p.func();
    }


}

class MyHandle implements InvocationHandler {


    //被代理的实例
    Object obj = null;

    //我要代理谁
    public MyHandle(Object obj) {
        this.obj = obj;

    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        Object result = method.invoke(this.obj, args);
        return result;
    }

}

interface IPeople {

    public void fun();

    public void func();
}

//实际被代理的类
class People implements IPeople {

    @Override
    public void fun() {
        System.out.println("这是fun方法");

    }

    @Override
    public void func() {
        System.out.println("这是func方法");

    }

}